import axios from 'axios'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import {useUserStore} from '@/stores/use'
import router from '@/router'
//创建axios实例
const http = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 5000
})
// axios请求拦截器
http.interceptors.request.use(config => {
  // 从pinia中获取token
  const userStore = useUserStore()
  const token = userStore.userInfo.token
  // 如果有token，则在请求头中添加token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, e => Promise.reject(e))

// axios响应式拦截器
http.interceptors.response.use(res => res.data, e => {
  const userStore = useUserStore()
  // 统一的错误处理
  ElMessage({
    type: 'error',
    message: e.response.data.message || '网络请求失败'
  })
  // 如果token失效，则清除token
  if (e.response.status === 401) {
    userStore.clearUserInfo()
    // 跳转到登录页面
    router.push('/login')
  }
  return Promise.reject(e)
})
//默认导出http实例
export default http